<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<template>
  <div class="app-container">
    <div class="">
      <el-form :inline="true" :model="listQuery">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item>
              <el-button v-waves type="primary" icon="el-icon-refresh" class="filter-item" @click="getList">刷新</el-button>
              <el-button v-if="treeDefaultExpand" v-waves type="primary" icon="el-icon-caret-top" class="filter-item" @click="clickSwitchExpand(false)">全部收起</el-button>
              <el-button v-else v-waves type="primary" icon="el-icon-caret-bottom" class="filter-item" @click="clickSwitchExpand(true)">全部展开</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex;flex-direction: row-reverse">
            <el-form-item>
              <el-button v-waves type="primary" icon="el-icon-circle-plus-outline" class="filter-item" @click="clickCreate">新增分类</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-table
      ref="refTreeTable"
      v-loading="listLoading"
      :header-cell-style="{ background:'#eef1f6',color:'#606266' }"
      border
      :data="tree"
      stripe
      row-key="id"
      :indent="20"
      :tree-props="{ children: 'children' }"
      :default-expand-all="treeDefaultExpand"
      @selection-change="handleSelectionChange"
    >
      <el-table-column fixed="left" label="分类名称" min-width="160px">
        <template v-slot="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="left" label="标识符" prop="code" />
      <el-table-column label="封面" prop="cover">
        <template v-slot="scope">
          <span>{{ scope.row.cover }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" />
      <el-table-column fixed="right" label="操作" width="200px">
        <template v-slot="scope">
          <el-button v-waves type="primary" size="mini" icon="el-icon-edit-outline" @click="clickUpdate(scope.row)">编辑</el-button>
          <el-button v-waves type="danger" size="mini" icon="el-icon-delete" @click="clickDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增|编辑弹窗 -->
    <el-dialog
      ref="drawer"
      :title="formTitle"
      :visible.sync="formVisible"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :destroy-on-close="true"
      :with-header="true"
      size="50%"
    >
      <div class="drawer-main" style="padding: 0 20px 0 20px;">
        <div class="drawer-main-content">
          <el-form ref="refForm" :model="form" :rules="rules" label-position="top" label-width="120px">
            <el-form-item label="" prop="parent_id">
              <template slot="label">
                上级分类
              </template>
              <el-cascader ref="cascader" v-model="form.parent_id" :options="tree" :props="{emitPath: false, value: 'id', label: 'name', checkStrictly: true}" filterable clearable style="width: 100%">
                <template v-slot="{ node, data }">
                  <span style="float: left;margin-right: 20px;">{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model.trim="form.name" clearable />
            </el-form-item>
            <el-form-item label="标识符" prop="code">
              <el-input v-model.trim="form.code" clearable />
            </el-form-item>
            <!--
            <el-form-item label="封面" prop="cover">
              <FileUpload :upload-index="1" :max-count="1" :show-image-max-count="1" image-tip="" image-width="40px" image-height="40px" @checkedFile="getCheckedFile" />
            </el-form-item>
            -->
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="demo-drawer__footer">
          <el-button v-waves style="width: 260px;" @click="formVisible = false">关闭</el-button>
          <el-button v-if="form.id === 0" v-waves type="primary" style="width: 260px;" @click="submitCreate()">确认新增</el-button>
          <el-button v-else v-waves type="primary" style="width: 260px;" @click="submitUpdate()">确认修改</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLessonCategoryList, lessonCategoryCreate, lessonCategoryUpdate, lessonCategoryDelete } from '@/api/lesson/lesson'
import { treeFormatEmpty } from '@/utils'
import clipboard from '@/utils/clipboard'
// import FileUpload from '@/components/FileUpload/index.vue'

export default {
  components: { },
  data() {
    return {
      tree: [],
      treeDefaultExpand: false,
      listLoading: false,
      listQuery: {
      },
      selectedIds: [],
      formTitle: '新增',
      formVisible: false,
      parentNode: {},
      form: {
        id: 0,
        parent_id: 0,
        name: '',
        code: '',
        cover: '',
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      drawerForm: {},
      labelTypeClassMap: {
        1: 'primary',
        2: 'success'
      },
      routes: [],
      drawerLoading: false,
      loadingDrawerSubmit: false
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getLessonCategoryList(this.listQuery).then(res => {
        this.tree = treeFormatEmpty(res.data)
      })
    },
    resetFormData() {
      this.form = {
        id: 0,
        parent_id: 0,
        name: '',
        code: '',
        cover: '',
        remark: ''
      }
    },
    clickCreate() {
      this.resetFormData()
      this.formTitle = '新增'
      this.formVisible = true
      this.parentNode = {}
    },
    submitCreate() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          lessonCategoryCreate(this.form).then(res => {
            this.getList()
            this.$message({
              message: '创建成功',
              type: 'success'
            })
            this.formVisible = false
          }).then(res => {
          })
        }
      })
    },
    clickUpdate(item) {
      this.form = {
        id: item.id,
        parent_id: item.parent_id,
        name: item.name,
        code: item.code,
        cover: item.cover,
        remark: item.remark
      }
      this.formTitle = '编辑'
      this.formVisible = true
    },
    submitUpdate() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          lessonCategoryUpdate(this.form).then(res => {
            this.getList()
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
            this.formVisible = false
          }).then(res => {
          })
        }
      })
    },
    clickDelete(item) {
      if (item.children && item.children.length > 0) {
        this.$message({ message: '存在子类，无法删除', type: 'error' })
        return
      }
      this.$confirm(`此操作将永久删除分类[${item.name}], 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitDelete(item.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitDelete(id) {
      lessonCategoryDelete({ id: id }).then(res => {
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.formVisible = false
      }).then(res => {
      })
    },
    handleSelectionChange(val) {
      if (val.length) {
        const ids = []
        val.forEach(function(item) {
          ids.push(item.id)
        })
        this.selectedIds = ids
      } else {
        this.selectedIds = []
      }
    },
    cascaderChange(val) {
      this.parentNode = this.$refs.cascader.getCheckedNodes()[0].data ?? {}
    },
    clickSwitchExpand(status) {
      this.treeDefaultExpand = status
      this.tree.forEach(v => {
        this.expandRowRecursive(v, status)
      })
    },
    // 递归展开/收起行
    expandRowRecursive(row, expand) {
      this.$refs.refTreeTable.toggleRowExpansion(row, expand)
      if (row.children) {
        row.children.forEach(child => {
          this.expandRowRecursive(child, expand)
        })
      }
    },
    handleCopy(text, event) {
      clipboard(text, event)
    },
    getCheckedFile(images, index) {
      this.form.cover = 'https://english-lesson-test.oss-cn-hangzhou.aliyuncs.com/EnglishStudyApp/lesson/2024/10/19/56bp120h880d4zulaiwt6hk100ll66z4.jpg'
      console.log('getCheckedFile', images, index)
    }
  }
}
</script>
